using System;
using System.Collections.Generic;
using System.Diagnostics;
using FilteredStatistics.Controller;

namespace FilteredStatistics.Common.Controller
{
    public class StatisticsController
    {
        private StatisticsController()
        {
        }

        public void RegisterProvider(object provider)
        {
            IStatisticsProvider newProvider;

            if (provider is IStatisticsProvider)
            {
                newProvider = provider as IStatisticsProvider;
            }
            else
            {
                newProvider = CreateStatisticProviderProxy(provider);

                Debug.Assert(newProvider != null);
            }

            m_Providers.Add(newProvider);

            RefreshTreeListColumns();
        }

        private IStatisticsProvider CreateStatisticProviderProxy(object provider)
        {
            IStatisticsProvider result = null;

            try
            {
                result = new ProxyStatisticsProvider(provider);
            }
            catch (Exception e)
            {
                Debug.Assert(false, e.Message);
            }

            return result;
        }

        public void RefreshTreeListColumns()
        {
            foreach(IStatisticsProvider provider in m_Providers)
            {
                IList<Guid> columnIds = provider.ColumnIds;

                foreach(Guid id in columnIds)
                {
                    Options.Instance.StatisticsColumnsManager.RegisterColumn(id, provider);
                }
            }
        }

        public static StatisticsController Instance
        {
            get
            {
                if (m_Instance == null)
                {
                    m_Instance = new StatisticsController();
                }

                return m_Instance;
            }
        }

        private static StatisticsController m_Instance = null;

        private List<IStatisticsProvider> m_Providers = new List<IStatisticsProvider>();
    }
}
